<?php

namespace App\Repositories\Impl;

use App\Models\CulturalHeritage;
use App\Repositories\Contracts\CulturalHeritageRepository;
use App\Repositories\Transformers\CulturalHeritageListTransformer;

class CulturalHeritageRepositoryImpl implements CulturalHeritageRepository
{
    public function paginate($perPage, $filter)
    {

        if (!empty($filter['keyword'])) {
            $culturalHeritage = CulturalHeritage::where('type', $filter['type'])->where('title', 'like', '%' . $filter['keyword'] . '%')
                ->orderBy('sort','desc')->orderBy('id','asc')->paginate($perPage);
        } else {
            $culturalHeritage = CulturalHeritage::where($filter)->orderBy('sort','desc')->orderBy('id','asc')->paginate($perPage);
        }

        $result = fractal($culturalHeritage, new CulturalHeritageListTransformer());

        return $result->toArray();

    }

    public function find($id, $columns = ['*'])
    {
        return CulturalHeritage::find($id, $columns);
    }

    public function findByFilter($filter, $columns = ['*'])
    {
        return CulturalHeritage::where($filter)->orderBy('sort','desc')->orderBy('id','desc')->get($columns);
    }

    public function store($data)
    {
        $culturalHeritage = CulturalHeritage::create($data);

        $result = fractal($culturalHeritage, new CulturalHeritageListTransformer());
        return $result->toArray();
    }

    public function update($data, $id)
    {
        return CulturalHeritage::whereId($id)->updateOrCreate($data);
    }

    public function updateByFilter($data, $where)
    {
        return CulturalHeritage::where($where)->update($data);
    }

    public function delete($id)
    {
        return CulturalHeritage::whereId($id)->delete();
    }
}
